<template>
  <el-card class="box-card">
    <div>
      <el-input class="userlist-input" placeholder="用户名" />
      <el-button type="primary" icon="el-icon-search">查询</el-button>
      <el-button>清空</el-button>
    </div>
    <div class="userlist-middle">
      <el-button type="primary">添加</el-button>
      <el-button type="danger" disabled>批量删除</el-button>
    </div>
    <el-table :data="items" v-loading="loading" border class="userlist-table">
      <el-table-column type="selection" align="center" />
      <el-table-column type="index" label="序号" align="center" width="50" />
      <el-table-column prop="username" label="用户名" align="center" />
      <el-table-column prop="nickName" label="用户昵称" align="center" />
      <el-table-column prop="roleName" label="权限列表" align="center" />
      <el-table-column prop="gmtCreate" label="创建时间" align="center" />
      <el-table-column prop="gmtModified" label="更新时间" align="center" />
      <el-table-column label="操作" align="center" width="200">
        <el-button type="info" icon="el-icon-user-solid" size="mini" />
        <el-button type="primary" icon="el-icon-edit" size="mini" />
        <el-button type="danger" icon="el-icon-delete" size="mini" />
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[5, 10, 20, 30, 50, 100]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />
  </el-card>
</template>

<script>
export default {
  name: 'UserList',
  data() {
    return {
      // 加载状态
      loading: false,
      // 当前页码
      page: 1,
      // 每页条数
      limit: 5,
      // 总条数
      total: 0,
      // 用户列表
      items: []
    }
  },
  watch: {
    // 返回数据中总页数发生变化时判断是否小于当前页数，若小于则再请求一次数据
    total() {
      const { page, limit, total } = this
      if (page > Math.ceil(total / limit)) {
        this.page = page - 1
        this.getUserList()
      }
    }
  },
  async mounted() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { page, limit } = this
      this.loading = true
      const {
        data: { total, items }
      } = await this.$API.user.reqGetUserList(page, limit)
      this.$message({ type: 'success', message: '获取数据成功' })
      this.total = total
      this.items = items
      this.loading = false
    },
    // 当前页数改变时触发
    handleCurrentChange(page) {
      this.page = page
      this.getUserList()
    },
    // 每页条数改变时触发
    handleSizeChange(limit) {
      this.limit = limit
      this.getUserList()
    }
  }
}
</script>

<style lang="scss" scoped>
.userlist-input {
  margin-right: 10px;
  width: 200px;
}
.userlist-middle {
  margin: 20px 0;
}
.userlist-table {
  margin-bottom: 20px;
}
</style>
